package com.doghome.news.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.doghome.news.annotation.CheckPermission;
import com.doghome.news.entity.Comment;
import com.doghome.news.entity.User;
import com.doghome.news.service.CommentService;
import com.doghome.news.utils.BizCode;
import com.doghome.news.utils.BizDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;

@RestController
public class CommentController {
	
	@Autowired
	private CommentService commentService;
	
	@Autowired
	private StringRedisTemplate srt;

	@RequestMapping("/commentByPage")
	public BizDto<PageInfo<Comment>> commentByPage(@RequestParam Map<String, Object> params){
		if(!params.containsKey("pageNum")|| !params.containsKey("pageSize")) {
			return new BizDto<PageInfo<Comment>>(BizCode.ERROR, "页码或页容量不能为空！", null);
		}
		
		PageInfo<Comment> pageInfo = commentService.selectByPage(params);
		return new BizDto<PageInfo<Comment>>(BizCode.SUCCESS, "成功", pageInfo);
	}
	
	@PostMapping("/addComment")
	@CheckPermission(permission = {1,2})
	public BizDto<Boolean> addComment(@RequestBody Comment comment,@RequestHeader(name = "Authorization") String token){
		BizDto<Boolean> bizDto = new BizDto<Boolean>();
		ObjectMapper objectMapper = new ObjectMapper();
		User user = null;
		try {
			user = objectMapper.readValue(srt.opsForValue().get(token), User.class);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		comment.setCauthor(user.getUname());
		comment.setCip("127.0.0.1");
		bizDto.setCode(BizCode.SUCCESS);
		bizDto.setData(commentService.addComment(comment));
		bizDto.setMsg("添加成功！");
		return bizDto;
	}
}
